// <copyright file="Service.cs" company="EnterpriseApi">
// Copyright (c) EnterpriseApi. All rights reserved.
// </copyright>

using System.Linq.Expressions;
using EnterpriseApi.Repositories;

namespace EnterpriseApi.Services;

/// <summary>
/// 通用服务实现类，提供基本的业务逻辑操作
/// </summary>
/// <typeparam name="TEntity">实体类型</typeparam>
public class Service<TEntity> : IService<TEntity> where TEntity : class
{
    private readonly IRepository<TEntity> _repository;

    /// <summary>
    /// 初始化Service的新实例
    /// </summary>
    /// <param name="repository">仓储实例</param>
    public Service(IRepository<TEntity> repository)
    {
        _repository = repository ?? throw new ArgumentNullException(nameof(repository));
    }

    /// <summary>
    /// 获取所有实体
    /// </summary>
    /// <returns>实体集合</returns>
    public async Task<IEnumerable<TEntity>> GetAllAsync()
    {
        return await _repository.GetAllAsync();
    }

    /// <summary>
    /// 根据条件获取实体
    /// </summary>
    /// <param name="predicate">查询条件</param>
    /// <returns>符合条件的实体集合</returns>
    public async Task<IEnumerable<TEntity>> GetByConditionAsync(Expression<Func<TEntity, bool>> predicate)
    {
        return await _repository.GetByConditionAsync(predicate);
    }

    /// <summary>
    /// 根据ID获取实体
    /// </summary>
    /// <param name="id">实体ID</param>
    /// <returns>实体对象，如果不存在则返回null</returns>
    public async Task<TEntity?> GetByIdAsync(int id)
    {
        return await _repository.GetByIdAsync(id);
    }

    /// <summary>
    /// 添加实体
    /// </summary>
    /// <param name="entity">要添加的实体</param>
    /// <returns>添加的实体</returns>
    public async Task<TEntity> AddAsync(TEntity entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException(nameof(entity));
        }

        return await _repository.AddAsync(entity);
    }

    /// <summary>
    /// 更新实体
    /// </summary>
    /// <param name="entity">要更新的实体</param>
    /// <returns>更新后的实体</returns>
    public async Task<TEntity> UpdateAsync(TEntity entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException(nameof(entity));
        }

        return await _repository.UpdateAsync(entity);
    }

    /// <summary>
    /// 删除实体
    /// </summary>
    /// <param name="id">要删除的实体ID</param>
    /// <returns>删除是否成功</returns>
    public async Task<bool> DeleteAsync(int id)
    {
        return await _repository.DeleteAsync(id);
    }
}